package com.taobao.classloader.impl;

import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taobao.classloader.ClassLoadStrategy;
import com.taobao.classloader.JarClassLoader;

public class PatternLoadStrategy implements ClassLoadStrategy {
	private static Logger	logger		= LoggerFactory.getLogger(PatternLoadStrategy.class);
	private Pattern			pattern;
	private String			regexString;
	private boolean			excludable	= false;

	@Override
	public Class<?> loadClass(String className, JarClassLoader jarClassLoader, ClassLoader parentClassLoader) {
		Class<?> clazz = null;
		if (!excludable && getPattern().matcher(className).find()) {
			clazz = jarClassLoader.loadClassFromResource(className);
		}
		if (clazz == null) {
			try {
				clazz = parentClassLoader.loadClass(className);
			} catch (ClassNotFoundException e) {
				logger.debug("Can't load class:{} from parent classLoader.", className);
			}
		}
		return clazz;
	}

	private Pattern getPattern() {
		if (pattern == null) {
			pattern = Pattern.compile(regexString);
		}
		return pattern;
	}

	public boolean isExcludable() {
		return excludable;
	}

	public void setExcludable(boolean excludable) {
		this.excludable = excludable;
	}

	public String getRegexString() {
		return regexString;
	}

	public void setRegexString(String regexString) {
		this.regexString = regexString;
	}

}
